package com.xiwen.xiwenzhang.role.controller;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiwen.common.baseentity.PageResultEntity;
import com.xiwen.common.baseentity.ResponsEntity;
import com.xiwen.common.utils.CommonConst;
import com.xiwen.common.utils.MenuTreeUtil;
import com.xiwen.common.utils.ResultUtil;
import com.xiwen.plugin.mybatisplus.generator.util.UtilsConst;
import com.xiwen.plugin.mybatisplus.pageinfo.PageInfo;
import com.xiwen.xiwenzhang.permission.Service.SysPermissionService;
import com.xiwen.xiwenzhang.permission.entity.SysPermissionEntity;
import com.xiwen.xiwenzhang.role.entity.SysRoleEntity;
import com.xiwen.xiwenzhang.role.service.RoleService;
import com.xiwen.xiwenzhang.user.entity.SysUserEntity;
import com.xiwen.xiwenzhang.user.service.UserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Slf4j
@Controller
@AllArgsConstructor
public class RoleController {

    @Autowired
    private final RoleService roleService;
    @Autowired
    private final UserService userService;
    @Autowired
    private final SysPermissionService permissionService;


    /**
     * @Dep 角色列表数据
     * @Author xiwen
     * @Date 2021/11/3 22:06
     */
    @GetMapping("/jumpRoleList")
    public String pageRoles(SysRoleEntity role, Model model) {
        try {
            return UtilsConst.ADMIN_PREFIX +"role/role-list";
        } catch (Exception e) {
            log.error(String.format("RoleController.loadRoles%s", e));
            throw e;
        }
    }

    /**
     * @Dep 获取角色列表
     * @Author xiwen
     * @Date 2021/11/27 19:11
     */
    @ResponseBody
    @PostMapping("/getRoleList")
    public PageResultEntity getRoleList(SysRoleEntity role) {
        try {
            Integer current = Integer.parseInt(role.getCurrent());
            Integer limit = Integer.parseInt(role.getLimit());
            Page<SysRoleEntity> page = new PageInfo<>(current, limit);
            Page<SysRoleEntity> rolePage = roleService.selectRoleList(role, page);
            PageResultEntity resultPage = ResultUtil.result(rolePage.getRecords(), rolePage.getTotal());
            return resultPage;

        } catch (Exception e) {
            throw e;
        }
    }
    /**
     * @Dep 新增角色
     * @Author xiwen
     * @Date 2021/11/27 19:11
     */
    @ResponseBody
    @PostMapping("/saveOrUpdateRole")
    public ResponsEntity saveOrUpdateRole(SysRoleEntity role) {
        try {
            boolean b = roleService.saveOrUpdate(role);
            if (b) {
                //shiroService.updatePermission();
                return ResultUtil.success("添加更新成功");
            } else {
                return ResultUtil.error("添加更新失败");
            }
        } catch (Exception e) {
            throw e;
        }
    }


    /**
     * @Dep 跳转添加或编辑菜单页面
     * @Author xiwen
     * @Date 2021/11/14 1:26
     */
    @GetMapping("/jumpAddOrUpdateRole")
    public String jumpAddOrUpdateRole(Model model,String id) {
        if (id!=null) {
            //编辑--查出数据再返回
            SysRoleEntity role = roleService.findRoleById(id);
            if (null != role) {
                model.addAttribute("role", role);
            }
        }
        //新增--直接返回页面
        return UtilsConst.ADMIN_PREFIX +"role/role-from";
    }

    /**
     * @Dep 删除角色
     * @Author xiwen
     * @Date 2021/11/15 22:22
     */
    @ResponseBody
    @PostMapping("/deleteRole")
    public ResponsEntity deleteRole(String id) {
        try {
            boolean b = roleService.removeById(id);
            if (b) {
                //shiroService.updatePermission();
                return ResultUtil.success("删除权限成功");
            } else {
                return ResultUtil.error("删除权限失败");
            }
        } catch (Exception e) {
            throw e;
        }
    }


    /**
     * 保存分配角色
     */
    @PostMapping("/saveAssignRole")
    @ResponseBody
    public ResponsEntity saveAssignRole(String roleIdStr,String userId) {
        ResponsEntity responsEntity;
        List<String> roleIdsList;
        String[] roleIds = roleIdStr.split(",");
        roleIdsList = Convert.convert(List.class, roleIds);
        //防止删掉超级管理员角色
        if(!roleIdsList.contains(CommonConst.ADMIN_ROLE) && userId.equals(CommonConst.ADMIN_ROLE)){
            roleIdsList.add(CommonConst.ADMIN_ROLE);
        }
        try {
            // 给用户分配角色
            userService.addAssignRole(userId, roleIdsList);
            responsEntity = ResultUtil.success("分配角色成功");
        } catch (Exception e) {
            System.out.println(e);
            responsEntity = ResultUtil.error("分配角色失败");
        }
        return responsEntity;
    }


    /**
     * @Dep 获取所有的权限列表
     * @Author xiwen
     * @Date 2021/12/6 18:37
     */
    @PostMapping("/getAssignPermissionList")
    @ResponseBody
    public List<SysPermissionEntity> getAssignPermissionList(String roleId) {
        List<SysPermissionEntity> menuList=permissionService.selectAll(roleId);
        MenuTreeUtil menuTreeUtil = new MenuTreeUtil();
        return menuTreeUtil.menuList(menuList);
    }

    /**
    * @Dep 分配权限
    * @Author xiwen
    * @Date 2021/12/6 22:06
    */
    @PostMapping("/assignPermission")
    @ResponseBody
    public ResponsEntity assignPermission(String roleId, String permissionIds) {
        List<String> permissionIdsList = new ArrayList<>();
        if (StringUtils.isNotBlank(permissionIds)) {
            String[] permissionIdArr= permissionIds.split(",");
            permissionIdsList = Arrays.asList(permissionIdArr);
        }
        try {
            roleService.addAssignPermission(roleId, permissionIdsList);
            /*重新加载角色下所有用户权限*/
            List<SysUserEntity> userList = roleService.findUserByRoleId(roleId);
            if (!userList.isEmpty()) {
                List<String> userIds = new ArrayList<>();
                for (SysUserEntity user : userList) {
                    userIds.add(user.getId());
                }
                //myShiroRealm.clearAuthorizationByUserId(userIds);
            }
            return ResultUtil.success("分配权限成功");
        } catch (Exception e) {
            System.out.println(e);
            return ResultUtil.error("分配权限失败");
        }
    }




}
